﻿<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加商品</title>
    <link rel="stylesheet" href="../css/from.css">
    <link rel="stylesheet" href="../themes/default/easyui.css">
    <link rel="stylesheet" href="../themes/icon.css">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/jquery.easyui.min.js"></script>
    <script src="../js/easyui-lang-zh_CN.js"></script>
    <script>
    var p=false;
        function loadSupplier() {
            $("#list").dialog({
                title: '供应商列表',
                width: 905,
                height: 400,
                closed: false,
                cache: false,
                modal: true
            });

        }
        function loadsell() {
        var supplierName=$("#supplierName").textbox("getValue");
        if(supplierName!=null&&supplierName!=''){
            $("#sellList").dialog({
                title: '销售订单列表',
                width: 905,
                height: 400,
                closed: false,
                cache: false,
                modal: true
            });
			}else{
        	alert("请选择客户名称")
        }
        }
     /*    function closeDg(name) {
            $("#supplierName").val(name);
            $("#list").dialog("close");
        } */
        function loadPart() {
        var supplierName=$("#supplierName").textbox("getValue");
        if(supplierName!=null&&supplierName!=''){
        	$("#partList").dialog({
                title: '选择配件',
                width: 1000,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           });
        }else{
        	alert("请选择客户名称")
        }
        }
/*         function closePart() {
            $("#partList").dialog("close");
        } */
         function myformatter(date){
          var y=date.getFullYear();
          var m=date.getMonth()+1;
          var d=date.getDate();
          var hh=date.getHours();
          var mm=date.getMinutes();
          var ss=date.getSeconds();
          return y+"-"+(m<10?('0'+m):m)+"-"+(d<10?('0'+d):d)+" "+(hh<10?('0'+hh):hh)+":"+(mm<10?('0'+mm):mm)+":"+(ss<10?('0'+ss):ss);
        }
         //用于将子页面的数据绑定到相关元素上
        function bindValue(data){
        	var name=data[0];
        	var linkman=data[1];
        	var phone=data[2];
        	var fax=data[3];
        	var address=data[4];
        	$('#supplierName').textbox('setValue',name);	
        	$('#contacter').textbox('setValue',linkman);	
        	$('#phone').textbox('setValue',phone);	
        	$('#fax').textbox('setValue',fax);	
        	$('#address').textbox('setValue',address);	
        }
        //销毁
         function closeSon(){
        	$("#list").dialog("destroy");
        	$("#absolute").html("<div id='list'  style='display: none' data-options='onClose:function(){closeSon()}'>"+
        	"<iframe src='company.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        
        function closePart() {
            $("#partList").dialog("destroy");
        	$("#part_List_parent").html("<div id='partList'  style='display: none' data-options='onClose:function(){closePart()}'>"+
        	"<iframe src='addPart.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        
        function closeSell() {
            $("#sellList").dialog("destroy");
        	$("#sellparent").html("<div id='sellList'  style='display: none' data-options='onClose:function(){closeSell()}'>"+
        	"<iframe src='sellOrder.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        
        
        
        $(function(){
        	$.ajax({
        		url:"/kxmanage/osb/code?prefix=CK",
        		type:"post",
        		dataType:"json",
        		success:function(data){
        			$("#code").textbox('setValue',data.result)
        		}
        	});
        	var newdate=new Date();
        	
        	$("#addDate").datetimebox("setValue",myformatter(newdate))
        	
        	
              $("#generatingParts").datagrid({
                checkOnSelect:true,
                rownumbers:true,
                columns:[[
                    {field:'ordercode',title:'销售订单',width:150},
                    {field:'code',title:'配件号',width:150},
                    {field:'partName',title:'配件名称',width:180},
                    {field:'partBrand',title:'配件品牌',width:70},
                    {field:'partNo',title:'配件型号',width:70},
                    {field:'amount',title:'数量',width:80,
                    formatter:function(value,row,index){
                    if(row.avg==null){
                    		return value;
                    	}
                            return '<input name="amount" onchange="change_amount_sellPrice('+index+',this)" type="number" value="'+value+'" style="width:30px;"/>';
                        }
                    },
                    {field:'avg',title:'单价(￥)',width:80,
                     formatter:function(value,row,index){
                     if(row.avg==null){
                    		return null;
                    	}
                            return '<input name="avg" onchange="change_amount_sellPrice('+index+',this)" type="number" value="'+value+'" style="width:50px;"/>';
                        }
                    },
                    {field:'price',title:'金额(￥)',width:80},
                    {field:'tuihuo',title:'所属仓库',width:78,formatter:function(value,row,index){
                    	if(row.avg==null){
                    		return null;
                    	}
                    	var str="主仓库"
                    	return str;
                    	}}, 
                    
                    {field:'memo',title:'备注',width:100,
                    formatter:function(value,row,index){
                     if(row.avg==null){
                    		return null;
                    	}
                    	if(value==null||value==''){
                    		value='';
                    	}
                            return '<input name="memo" onchange="onChange_Memo('+index+',this)" type="text" value="'+value+'" style="width:80px"/>';
                        }
                    }, 
                   	{field:'opt',title:'操作',width:84,formatter:function (value,row,index) {
                            if(row.avg==null){
    	                		return null;
	                    	}
                            var context="<a  href=\"javascript:del('"+index+"')\">删除</a>&nbsp;&nbsp;"
                            return context;
                        }}
                	]],
                	onClickRow:function(index,data){
                	$(this).datagrid('unselectRow',index);
                }
        	})
        $("#add").click(function(){
			var ist=$("input[name='kp']:checked").val();//是否开票
			var form=$("#form").serialize();
				var oldRow=$('#generatingParts').datagrid('getRows');
				var data =JSON.stringify($('#generatingParts').datagrid('getData').rows);
        	if(oldRow==null||oldRow==''){
        		alert("没有添加配件信息");
        	}else{
        		var money=parseFloat(oldRow[oldRow.length-1]['price']);
        		$.ajax({
        		type:"get",
        		url:"/kxmanage/osb/add?"+form,
        		data:{'data':data,'money':money},
        		dataType:"json",
        		success:function(data){
        			if(data.result=="success"){
        				alert("添加成功");
        				parent.addTabs('出库单据管理','goods/outstorageBill.jsp');
        				parent.closeTabs('出库单');
        			}else if(data.result=="noPower"){
        				alert("您没有权限！");
        			}else{
        				alert("添加错误");
        			}
        		}
        		});
        	}
        });
        $("#check_btn").click(function(){
        	var ist=$("input[name='kp']:checked").val();//是否开票
			var form=$("#form").serialize();
				var oldRow=$('#generatingParts').datagrid('getRows');
				var data =JSON.stringify($('#generatingParts').datagrid('getData').rows);
        	if(oldRow==null||oldRow==''){
        		alert("没有添加配件信息");
        	}else{
        		var money=parseFloat(oldRow[oldRow.length-1]['price']);
        		$.ajax({
        		type:"get",
        		url:"/kxmanage/osb/add?"+form,
        		data:{'data':data,'money':money},
        		dataType:"json",
        		success:function(data){
        			if(data.result=="success"){
        			  var status=2;
					  var outcode=$("#code").val();
					  var data=JSON.stringify($('#generatingParts').datagrid('getData').rows);//配件信息
					  $.ajax({
					  	url:"/kxmanage/osb/upstatus",
					  	data:{'status':status,'outcode':outcode,'data':data},
					  	dataType:"json",
					  	type:"get",
					  	success:function(data){
							if(data.result=="success"){
								alert("审核成功");
								location.href="/kxmanage/osb/modifytwo?code="+outcode;
							}else if(data.result=="repeat"){
								alert("销售订单已出库，审核不能通过");
							}else if(data.result=="less"){
								alert(data.code+"库存数量不足，审核失败");							
							}else if(data.result=="noPower"){
        						alert("您没有权限！");
        					}else{
								alert("审核失败");
							}					  	
					  	}
					  });
        				
        			}else{
        				alert("添加错误");
        			}
        		}
        		});
        	}
        });
        });
      
         //用于将子页面的数据绑定到相关元素上
        function addpart(row,part){
            var flag=true;
            var x=true;
            var oldRow=$('#generatingParts').datagrid('getRows');
            
            for(var i=0;i<row.length;i++){
               if(oldRow!=null&&oldRow!=''){
                 for(var j=0;j<oldRow.length;j++){
                   if(oldRow[j]['code']==row[i]['code']){
         		       alert("不能添加重复配件");
         		       flag=false;
         		       break;
         		   }
                 } 
                 if(flag==true){
                 }else{
                 	break;
                 }
                }else{
                	addToPage(row[i],part);
                	x=false;
                }
             }
             if(flag==true){
             	if(x==true){
                 	for(var i=0;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage(row[i],part);
					}
                }else{
                 	for(var i=1;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage(row[i],part);
					}	
                }
              }
	              closePart();
         }
        
          //用于将子页面的数据绑定到相关元素上
        function addsellpart(row,part){
            var flag=true;
            var x=true;
            var oldRow=$('#generatingParts').datagrid('getRows');
            
            for(var i=0;i<row.length;i++){
               if(oldRow!=null&&oldRow!=''){
                 for(var j=0;j<oldRow.length;j++){
                 
                   if(oldRow[j]['billcode']==row[i]['billcode']&&oldRow[j]['code']==row[i]['code']){
         		       alert("不能添加重复订单");
         		       flag=false;
         		       break;
         		   }
                 } 
                 if(flag==true){
                 }else{
                 	break;
                 }
                }else{
                	addToPage(row[i],part);
                	x=false;
                }
             }
             if(flag==true){
             	if(x==true){
                 	for(var i=0;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage(row[i],part);
					}
                }else{
                 	for(var i=1;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage(row[i],part);
					}	
                }
              }
	             closeSell();
         }
        
        
        function addToPage(row,part){
         	  if(part=="sellpart"){
	            $('#generatingParts').datagrid('appendRow',{
				ordercode: row.billcode,
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: row.amount,
				avg: row.avg,
				price: row.price,
				memo: row.memo,
				opt: row.opt
		   		});
              }else if(part=="part"||part==null){
	            $('#generatingParts').datagrid('appendRow',{
				ordercode: row.billcode,
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: 1,
				avg: row.sellPrice,
				price: row.sellPrice,
				memo: row.memo,
				opt: row.opt
		   });
              }
           
		   
		   $("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
          });
        }
        
          function total(col){
        	var rows=$("#generatingParts").datagrid('getRows');
        	var total=0;
        	for(var i=0;i<rows.length;i++){
        		total+=parseFloat(rows[i][col]);
        	}
        	return total;
          }
        //单价或数量注入data  
        function change_amount_sellPrice(input_index,input){
        
         	var amount=$(input).parent().parent().parent().find('[name="amount"]').val();
         	var avg=$(input).parent().parent().parent().find('[name="avg"]').val();
         	var price=parseFloat(amount)*parseFloat(avg);
         	$('#generatingParts').datagrid('updateRow',{
				index: input_index,
				row: {
					amount: amount,
					avg:avg,
					price: price
				}
			});
			var oldRow=$('#generatingParts').datagrid('getRows');
			$('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
			$("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           	});
         }
         //备注注入data
         function onChange_Memo(index,input){
          var memo=$(input).parent().parent().parent().find('[name="memo"]').val();
          $("#generatingParts").datagrid('updateRow',{
               index: index,
	           row: {
		          memo:memo
	           }
          });
         } 
            function del(index){
         	//删除当前行
         	$('#generatingParts').datagrid('deleteRow',index);
         	//拿到之前的数据并重新封装，刷新index
         	var oldData=$('#generatingParts').datagrid('getData');
         	$('#generatingParts').datagrid('loadData',oldData);
         	//更新最后一行
         	var oldRow=$('#generatingParts').datagrid('getRows');
         	$('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
			$("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           	});
           	if(oldRow.length==1){
           		$('#generatingParts').datagrid('deleteRow',oldRow.length-1);
           	}
         }
         
         function loadadd(){
         	location.reload();
         }
         function closeself(){
         	parent.closeTabs("出库单");
         }
         
    </script>
    <style>
        body {
            font-size:12px;
            padding:10px
        }
        .l-table-edit {
           border-collapse:collapse;
           boreder-spacing:0
        }
        .l-table-edit-td {
            padding:4px;
            font-size:12px;
             border:#84a0c4 1px solid
        }
        
    </style>


</head>
<body>
<form name="form"  id="form" action="" method="post">
    <table cellpadding="0"  cellspacing="0" class="l-table-edit" style="width:100%"  >
        <tr >
            <td width="17%"  align="right" class="l-table-edit-td">出库单号：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input class="easyui-textbox" name="code" type="text" id="code"  size="30" maxlength="100" ltype="text" /></td>
            <td width="13%"  align="right" class="l-table-edit-td">出库日期：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input class="easyui-datetimebox" name="outstorageDate"  id="addDate"  style="width:168px"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">
                <a href="javascript:loadSupplier()">客户名称</a>：
            </td>
            <td align="left" class="l-table-edit-td">
                <input class="easyui-textbox" name="customName" type="text" id="supplierName"  value=""  maxlength="100" ltype="text"  style="width:239px"/>
            <td width="13%" align="right" class="l-table-edit-td">联系人员：</td>
            <td align="left" class="l-table-edit-td">
                <input class="easyui-textbox" name="linkname" type="text" id="contacter" value="" maxlength="30" ltype="text" /></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">电&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;话：</td>
            <td align="left" class="l-table-edit-td"><input class="easyui-textbox" name="phone"  type="text" id="phone" value="" size="30" maxlength="50" ltype="text" /></td>
            <td width="17%" align="right" class="l-table-edit-td">出库方式：</td>
            <td align="left" class="l-table-edit-td">
            <select name="outstorageType" id="outtype">
            		<option value="1">销售出库</option>
					<option value="2">其他出库</option>
			</select></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">传&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;真：</td>
            <td align="left" class="l-table-edit-td"><input class="easyui-textbox" type="text" id="fax" name="fax" value="" size="30" maxlength="50" ltype="text" /></td>
            <td width="17%" align="right" class="l-table-edit-td">是否开票：</td>
            <td align="left" class="l-table-edit-td">
				<input type="radio" name="kp" checked value="1"/>是<input type="radio" name="kp" value="2"/>否
			</td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址：</td>
            <td align="left" class="l-table-edit-td"><input class="easyui-textbox" type="text" id="address" name="address"  value="" size="30" maxlength="50" ltype="text" /></td>
            <td width="17%" align="right" class="l-table-edit-td">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注：</td>
            <td align="left" class="l-table-edit-td"><input class="easyui-textbox" name="memo" type="text"  class="l-table-edit" id="memo" value="" maxlength="50"  ltype="text" style="width:168px"/>
            <input type="hidden" value="1" name="payStatus">
            <input type="hidden" value="1" name="checkStatus">
            </td>
        </tr>
        
    </table>
</form>
<br>
<a href="javascript:loadadd()"><input  type="button" value="新   增" style="width:60px"></a>
<a href="javascript:loadsell()"><input  type="button" value="销售单" style="width:60px"></a>
<a href="javascript:loadPart()"><input  type="button" value="添加配件" style="width:60px"></a>
<input  type="button" id="add" value="保存" style="width:60px">
<input  type="button" id="check_btn" value="审核" style="width:60px" />
<a href="javascript:closeself()"><input  type="button" value="关闭" style="width:60px"></a>


<div id="generatingParts" class="easyui-datagrid">
</div>
<div id="absolute">
<div id="list"  style="display: none" data-options="onClose:function(){closeSon()}">
    <iframe src='company.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
</div>
</div>
<div id="part_List_parent">
<div id="partList"  style="display: none" data-options="onClose:function(){closePart()}">
    <iframe src='addPart.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
</div>
</div>
<div id="sellparent">
<div id="sellList"  style="display: none" data-options="onClose:function(){closeSell()}">
    <iframe src='sellOrder.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
</div>
</div>
</body>
</html>